#Copyright Jon Berg , turtlemeat.com

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from socket import inet_aton
import re
import urlparse
import bencode
import struct


def toHex(s):
    lst = []
    for ch in s:
        hv = hex(ord(ch)).replace('0x', '')
        if len(hv) == 1:
            hv = '0'+hv
        lst.append(hv)
    
    return reduce(lambda x,y:x+y, lst)

p_announce = re.compile('/announce\?.*')

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
#        try:
        if(re.match(p_announce, self.path)):
            request = self.path[self.path.find('?')+1:]
            params = urlparse.parse_qs(request)
            params['info_hash'] = toHex(params['info_hash'][0])
            print(params['info_hash'])
            print(self.client_address)
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()

        response = {'interval':10,
                    'tracker id':'BBQ',
                    'complete':1,
                    'incomplete':1,
                    #'peers':{'peer id':'toto', 'ip':'127.0.0.1', 'port':'8888'}
                    'peers':inet_aton('192.168.0.42')+struct.pack(">H",8888)+inet_aton("192.168.0.42")+struct.pack(">H",23957)+inet_aton("192.168.0.2")+struct.pack(">H",8888)
                    }

        self.wfile.write(bencode.bencode(response))
#        f.close()
        return                                      
#        except IOError:
#            self.send_error(404,'File Not Found: %s' % self.path)
     

#    def do_POST(self):
#        global rootnode
#        try:
#            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
#            if ctype == 'multipart/form-data':
#                query=cgi.parse_multipart(self.rfile, pdict)
#            self.send_response(301)
#            
#            self.end_headers()
#            upfilecontent = query.get('upfile')
#            print "filecontent", upfilecontent[0]
#            self.wfile.write("<HTML>POST OK.<BR><BR>");
#            self.wfile.write(upfilecontent[0]);
#            
#        except :
#            pass

def main():
    try:
        server = HTTPServer(('', 9999), MyHandler)
        print('started httpserver...')
        server.serve_forever()
    except KeyboardInterrupt:
        print('^C received, shutting down server')
        server.socket.close()

if __name__ == '__main__':
    main()

